//
//  USAddPhotoAlbumController.m
//  us
//
//  Created by karry on 2025/4/8.
//

#import "USAddPhotoAlbumController.h"
#import <PhotosUI/PhotosUI.h>
#import <PencilKit/PencilKit.h>

#import "USAlbumCoverView.h"
#import "USToolBar.h"
#import "USAlbumCoverColorChooseBar.h"
#import "USAlbumEditController.h"
#import <WXSTransition/UINavigationController+WXSTransition.h>
#import "USStickerPickerView.h"
#import "USAlbumStyleView.h"
#import "IRStickerView.h"
#import "IRTextView.h"
#import "USAlbumDrawView.h"
@interface USAddPhotoAlbumController ()<PHPickerViewControllerDelegate,USStickerPickerViewDelegate,USAlbumStyleViewDelegate,IRStickerViewDelegate,IRTextViewDelegate,USAlbumDrawViewDelegate,PKCanvasViewDelegate,UIColorPickerViewControllerDelegate>

@property (nonatomic,strong) USAlbumCoverView *coverView;
@property (nonatomic,strong) USToolBar *toolBar;
@property (nonatomic,strong) USAlbumCoverColorChooseBar *colorChooseBar;

@property (nonatomic,strong) USStickerPickerView *stickerView;
@property (nonatomic,strong) USAlbumStyleView *styleView;
@property (nonatomic,strong) USAlbumDrawView *drawView;

@property (nonatomic, assign) BOOL isDrawing;

@property (nonatomic, strong) UIBarButtonItem *undoItem;
@property (nonatomic, strong) UIBarButtonItem *redoItem;

@property (nonatomic, strong) PKCanvasView *canvasView;
@property (nonatomic, strong) PKInkingTool *pen;
@property (nonatomic, strong) PKEraserTool *eraser;
@property (nonatomic, strong) UIColor *penColor;
@property (nonatomic, assign) CGFloat penWidth;

@property (nonatomic, strong) IRStickerView *selectedSticker;

@end

@implementation USAddPhotoAlbumController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [USFeedbackTool impactSoft];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_close"] style:UIBarButtonItemStylePlain target:self action:@selector(closeAction:)];
 
    [self setupView];
}

- (void)setupView{
    
    CGFloat w = MIN(self.view.jk_width, self.view.jk_height) - 30 * 2;
    
    CGFloat h = w * 424/345.f;
    
    USAlbumCoverView *coverView = [[USAlbumCoverView alloc]initWithFrame:CGRectMake(0, 0, w, h)];
    _coverView = coverView;
    
    coverView.clipsToBounds = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [coverView addGestureRecognizer:tap];
        
    [self.view addSubview:coverView];

    [coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(w);
        make.height.mas_equalTo(h);
        make.centerX.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.view.mas_centerY).mas_offset(-30);
    }];
    
    if (self.album) {
     
        self.coverView.color = [UIColor jk_colorWithHexString:self.album.color];
        if (self.album.coverUrl.length > 0) {
            [coverView.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.album.coverUrl]];
        }
        self.coverView.coverType = self.album.coverType;
    }else{
        self.coverView.color = [UIColor jk_colorWithHexString:@"#DCEAF8"];

    }
    
    UIButton *drawBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [drawBtn setImage:[UIImage imageNamed:@"icon-3"] forState:0];
    [drawBtn addTarget:self action:@selector(drawAction) forControlEvents:UIControlEventTouchUpInside];

    UIButton *txtBtn = [UIButton buttonWithType:UIButtonTypeCustom];;
    [txtBtn setImage:[UIImage imageNamed:@"icon-2"] forState:0];
    [txtBtn addTarget:self action:@selector(textAction) forControlEvents:UIControlEventTouchUpInside];

    UIButton *stickerBtn = [UIButton buttonWithType:UIButtonTypeCustom];;
    [stickerBtn setImage:[UIImage imageNamed:@"icon-1"] forState:0];
    [stickerBtn addTarget:self action:@selector(stickerAction) forControlEvents:UIControlEventTouchUpInside];

    UIButton *styleBtn = [UIButton buttonWithType:UIButtonTypeCustom];;
    [styleBtn setImage:[UIImage imageNamed:@"icon-0"] forState:0];
    [styleBtn addTarget:self action:@selector(styleAction) forControlEvents:UIControlEventTouchUpInside];


    self.toolBar = [[USToolBar alloc]initWithButtons:@[styleBtn,stickerBtn,txtBtn,drawBtn] layoutType:USToolBarLayoutTypeLeft];
    [self.view addSubview:self.toolBar];
    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
    }];
    
    self.colorChooseBar = [[USAlbumCoverColorChooseBar alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 50)];
    self.colorChooseBar.color = self.coverView.color;
    @weakify(self)
    self.colorChooseBar.didChooseColorBlock = ^(UIColor * color) {
        @strongify(self)
        self.coverView.color =color;
    };
    
    [self.colorChooseBar.addBgBtn addTarget:self action:@selector(chooseBgPhoto:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.colorChooseBar];
    [self.colorChooseBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_equalTo(self.toolBar.mas_top);
    }];
    
    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIButtonConfiguration *config = [UIButtonConfiguration filledButtonConfiguration];
    config.attributedTitle = [[NSAttributedString alloc]initWithString:@"下一步" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15 weight:UIFontWeightMedium]}];
    doneBtn.tintColor = UIColor.labelColor;
    [doneBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    config.contentInsets = NSDirectionalEdgeInsetsMake(8, 12, 8, 12);
    doneBtn.configuration = config;
    
    [self.toolBar addSubview:doneBtn];
    [doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-20);
        make.centerY.mas_equalTo(self.toolBar.contentView);
    }];
    
    
    [self.view addSubview:self.stickerView];
    CGFloat stickerViewH = 324 + 12 + self.view.window.safeAreaInsets.bottom;
    [self.stickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_offset(stickerViewH);
        make.height.mas_equalTo(stickerViewH);
    }];
    
    [self.view addSubview:self.styleView];
    CGFloat styleViewH = 158 + 44 + self.view.window.safeAreaInsets.bottom;
    [self.styleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_offset(styleViewH);
        make.height.mas_equalTo(styleViewH);
    }];
    
    [self.view addSubview:self.drawView];
//    CGFloat drawViewH = 52 + 20 + 72 + self.view.window.safeAreaInsets.bottom;
    CGFloat drawViewH = 52 + 20 + 72 + 30;
    [self.drawView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_offset(drawViewH);
        make.height.mas_equalTo(drawViewH);
    }];
    
    self.penColor = [UIColor jk_colorWithHexString:self.drawView.colorGroups.firstObject];
    self.penWidth = 5.0;
    self.pen = [[PKInkingTool alloc] initWithInkType:PKInkTypePen color:self.penColor width:self.penWidth];
    self.canvasView.tool = self.pen;
    
    UIBarButtonItem *redoItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"redo_enable"] style:UIBarButtonItemStylePlain target:self action:@selector(redoAction)];
    
    UIBarButtonItem *undoItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"undo_enable"] style:UIBarButtonItemStylePlain target:self action:@selector(undoAction)];
        
    self.undoItem = undoItem;
    self.redoItem = redoItem;
    
    self.undoItem.enabled = NO;
    self.redoItem.enabled = NO;

    [RACObserve(self, isDrawing)subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if (self.isDrawing) {
            self.title = @"";
            self.navigationItem.rightBarButtonItems = @[self.doneItem,redoItem,undoItem];

            self.canvasView.userInteractionEnabled = YES;
            [self.canvasView becomeFirstResponder];

        }else{
            self.title = @"编辑相册封面";
            self.navigationItem.rightBarButtonItems = @[];

            self.canvasView.userInteractionEnabled = NO;
            [self.canvasView resignFirstResponder];

        }
    }];
}

- (USStickerPickerView *)stickerView {
    if (_stickerView == nil) {
        self.stickerView = [[USStickerPickerView alloc]initWithStickerShowCloseButton:YES];
        self.stickerView.delegate = self;
        self.stickerView.hidden = YES;
    }
    return _stickerView;
}

- (USAlbumStyleView *)styleView {
    if (_styleView == nil) {
        self.styleView = [[USAlbumStyleView alloc]init];
        self.styleView.delegate = self;
        self.styleView.hidden = YES;
    }
    return _styleView;
}

- (USAlbumDrawView *)drawView {
    if (_drawView == nil) {
        self.drawView = [[USAlbumDrawView alloc]init];
        self.drawView.delegate = self;
        self.drawView.hidden = YES;
        
    }
    return _drawView;
}
 

- (PKCanvasView *)canvasView{
    if (!_canvasView) {
        
        _canvasView = [[PKCanvasView alloc]initWithFrame:CGRectZero];
        _canvasView.backgroundColor = [UIColor clearColor];
        _canvasView.opaque = NO;
        _canvasView.scrollEnabled = false;
        _canvasView.userInteractionEnabled = false;
        _canvasView.delegate = self;
        _canvasView.drawingPolicy = PKCanvasViewDrawingPolicyAnyInput; // 支持 Apple Pencil 和手指

        [self.coverView.bgContentView addSubview:_canvasView];
        
        self.eraser = [[PKEraserTool alloc] initWithEraserType:PKEraserTypeBitmap];
        self.pen = [[PKInkingTool alloc] initWithInkType:PKInkTypePen color:self.penColor width:5];
        self.canvasView.tool = self.pen;

        [_canvasView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.coverView.bgContentView);
        }];
        
    }
    return _canvasView;
}
 
- (void)stickerAction{
    [USFeedbackTool impactSoft];
    [self disableSelectSticker];

    [self.stickerView showStickerPicker];
}
- (void)textAction {
    [self disableSelectSticker];
    
    IRTextView *textView = [[IRTextView alloc] initWithContentFrame:CGRectMake(self.coverView.bgContentView.jk_width * 0.5 - 50, self.coverView.bgContentView.jk_height*0.5 - 20, 100, 40)];
    textView.enabledControl = YES;
    textView.enabledBorder = YES;
    textView.tag = 1;
    textView.delegate = self;
    [self.coverView.bgContentView addSubview:textView];
    [textView performTapOperation];
}
- (void)styleAction {
    [USFeedbackTool impactSoft];
    [self disableSelectSticker];

    [self.styleView styleAppear];
}
- (void)drawAction {
    [USFeedbackTool impactSoft];
    [self disableSelectSticker];

    self.isDrawing = YES;

    [self.drawView drawAppear];
}
- (void)doneAction:(id)sender{
    [super doneAction:sender];
    
    self.isDrawing = NO;
     

    [self.drawView drawAppear];

}
- (void)undoAction{
    [USFeedbackTool impactSoft];

    if (self.canvasView.undoManager.canUndo) {
        [self.canvasView.undoManager undo];
    }else{
        self.undoItem.enabled = self.canvasView.undoManager.canUndo;
    }
}

- (void)redoAction{
    
    [USFeedbackTool impactSoft];

    if (self.canvasView.undoManager.canRedo) {
        [self.canvasView.undoManager redo];
    }else{
        self.redoItem.enabled = self.canvasView.undoManager.canRedo;
    }
    
}
//MARK:单机手势
- (void)tapAction:(UITapGestureRecognizer *)sender{
    
//    if (self.isDrawing) {
//        self.isDrawing = false;
//    }
//    
//    [self clearInputView];
    
    if (self.selectedSticker) {
        self.selectedSticker.enabledControl = NO;
        self.selectedSticker.enabledBorder = NO;
        
        if ([self.selectedSticker isKindOfClass:[IRTextView class]]) {
            IRTextView *textView = (IRTextView *)self.selectedSticker;
            [textView.contentTextView resignFirstResponder];
        }
        
        self.selectedSticker = nil;
        return;
    }
    
    CGPoint point = [sender locationInView: self.coverView];
    for (UIView *view in self.coverView.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"IRStickerView")]) {
            
            if (CGRectContainsPoint(view.frame, point)) {
                IRStickerView *sticker = (IRStickerView *)view;
                [sticker performTapOperation];
                
                return;
            }
        }
    }
 
    
//    UITextView *textView = (UITextView *)sender.view;
//    if (!textView) {
//        return;
//    }
    
//    NSLayoutManager *layoutManager = textView.layoutManager;
//    CGPoint location = [sender locationInView:textView];
//    location.x -= textView.textContainerInset.left;
//    location.y -= textView.textContainerInset.top;
//    //防止误触
//    if (location.y < 0) {
//        return;
//    }
//    NSUInteger characterIndex = [layoutManager characterIndexForPoint:location inTextContainer:textView.textContainer fractionOfDistanceBetweenInsertionPoints:nil];
//    
//    if (characterIndex < textView.textStorage.length){
//        
//        ///找到图片
//        id value = [textView.attributedText attribute:NSAttachmentAttributeName atIndex:characterIndex effectiveRange:nil];
//        
//        if (value == nil) {
//            return;
//        }
//        //判断点在不在图片上
//        CGRect rect = [textView.layoutManager boundingRectForGlyphRange:NSMakeRange(characterIndex, 1) inTextContainer:textView.textContainer];
//        
//        if (CGRectContainsPoint(rect, location) == NO) {
//            return;
//        }
//        
//        if ([value isKindOfClass:[EMTextAttachment class]]) {
//            
//            EMMediaTextAttachment *data = [value data];
//            [self tapMediaData:data];
//            
//        }else if ([value isKindOfClass:[NSCheckBoxAttachment class]]){
//            
//            [EMFeedBackTool feedBack];
//            NSCheckBoxAttachment *attachment = (NSCheckBoxAttachment *)value;
//            attachment.isSelected = !attachment.isSelected;
//            [self.textView.layoutManager invalidateDisplayForCharacterRange:NSMakeRange(characterIndex, 1)];
//        }
        
//    }
    
}
#pragma mark USStickerPickerViewDelegate
- (void)stickerPickerViewClose {
    [self disableSelectSticker];
}
- (void)stickerPickerView:(USStickerPickerView *)picker didSelectSticker:(USStickerModel *)sticker{

    [self disableSelectSticker];
    
    IRStickerView *sticker1 = [[IRStickerView alloc] initWithContentFrame:CGRectMake(self.coverView.bgContentView.jk_width * 0.5 - 40, self.coverView.bgContentView.jk_height*0.5 - 40, 80, 80) contentImage:[UIImage imageNamed:sticker.name]];
    sticker1.contentImageName = sticker.name;
    sticker1.enabledControl = YES;
    sticker1.enabledBorder = YES;
    sticker1.tag = 1;
    sticker1.delegate = self;
    [self.coverView.bgContentView addSubview:sticker1];
    [sticker1 performTapOperation];
    
}

- (void)disableSelectSticker{
    
    if (self.selectedSticker) {
        self.selectedSticker.enabledControl = NO;
        self.selectedSticker.enabledBorder = NO;
        self.selectedSticker = nil;
    }
    
}
#pragma mark - UIColorPickerViewControllerDelegate

- (void)colorPickerViewControllerDidFinish:(UIColorPickerViewController *)viewController {
    UIColor *selectedColor = viewController.selectedColor;

    self.penColor = selectedColor;
    self.pen = [[PKInkingTool alloc] initWithInkType:PKInkTypePen color:selectedColor width:self.penWidth];
    self.canvasView.tool = self.pen;
}

 
#pragma mark - USAlbumDrawViewDelegate
- (void)albumDrawViewdidChooseColor {
 
    UIColorPickerViewController *colorPicker = [[UIColorPickerViewController alloc] init];
    colorPicker.delegate = self;
    colorPicker.selectedColor = UIColor.systemBlueColor; // 默认选中颜色
    colorPicker.supportsAlpha = YES; // 支持透明度选择
    [self presentViewController:colorPicker animated:YES completion:nil];
}


- (void)albumDrawViewdidSelectType:(NSInteger)type{
    if (type == 1) {
        self.canvasView.tool = self.eraser;
    }else{
        self.canvasView.tool = self.pen;
    }
}

- (void)albumDrawViewSelectColor:(UIColor *)color{
    self.penColor = color;
    self.pen = [[PKInkingTool alloc] initWithInkType:PKInkTypePen color:color width:self.penWidth];
    self.canvasView.tool = self.pen;

}

- (void)albumDrawViewPenWidth:(CGFloat)width {
    self.penWidth = width * 10;
    self.pen = [[PKInkingTool alloc] initWithInkType:PKInkTypePen color:self.penColor width:self.penWidth];
    self.canvasView.tool = self.pen;

}

#pragma mark - IRStickerView
//点击右上角
- (void)ir_StickerViewDidTapRightTopControl:(IRStickerView *)stickerView{
    
    stickerView.backgroundColor = [UIColor redColor];
    [stickerView removeFromSuperview];
}
//点击右下角
- (void)ir_StickerViewDidTapRightBottomControl:(IRStickerView *)stickerView{
    
}

- (void)ir_StickerViewDidTapLeftBottomControl:(IRStickerView *)stickerView{
    stickerView.isBelow = YES;
    [stickerView.superview insertSubview:stickerView atIndex:1];
    
}

- (void)ir_StickerViewDidTapLeftTopControl:(IRStickerView *)stickerView{
    stickerView.isBelow = NO;
    [stickerView.superview bringSubviewToFront:stickerView];
}

- (void)ir_StickerViewDidTapContentView:(IRStickerView *)stickerView {
    //NSLog(@"Tap[%zd] ContentView", stickerView.tag);
    if (self.selectedSticker) {
        self.selectedSticker.enabledBorder = NO;
        self.selectedSticker.enabledControl = NO;
    }
    self.selectedSticker = stickerView;
    self.selectedSticker.enabledBorder = YES;
    self.selectedSticker.enabledControl = YES;
    self.selectedSticker.isBelow = NO;
}


#pragma mark USAlbumStyleViewDelegate
- (void)albumStyleViewdidSelectStyle:(NSInteger)style {
    self.coverView.coverType = style;
    
}
/// @param canvasView The canvas view that changed.
- (void)canvasViewDrawingDidChange:(PKCanvasView *)canvasView API_AVAILABLE(ios(13.0)){
    
    if (canvasView.isFirstResponder == NO) {
        [canvasView becomeFirstResponder];
    }
    self.redoItem.enabled = canvasView.undoManager.canRedo;
    self.undoItem.enabled = canvasView.undoManager.canUndo;
     
    
}

#pragma mark - action

- (void)closeAction:(id)sender{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)chooseBgPhoto:(id)sender{
    
    [USFeedbackTool impactSoft];

    PHPickerConfiguration *config = [[PHPickerConfiguration alloc] init];
    config.selectionLimit = 1; // 只选一张图
    config.filter = [PHPickerFilter imagesFilter]; // 只显示图片

    PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:config];
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

// 代理回调
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    PHPickerResult *result = results.firstObject;
    if (result) {
        [result.itemProvider loadObjectOfClass:[UIImage class] completionHandler:^(UIImage *image, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (image) {
                    // ✅ 使用选中的图片
                    self.coverView.bgImageView.image = image;
                }
            });
        }];
    }
}


- (void)nextAction:(id)sender{
    
    [USFeedbackTool impactRigid];
    
    [self disableSelectSticker];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UIImage *image = [self.coverView jk_screenshot];
        
        USAlbumEditController *vc = [[USAlbumEditController alloc]init];
        if (self.album) {
            vc.album = self.album;
        }
        vc.imageView.image = image;
        vc.image = image;
        vc.imageNoLine = [self.coverView snapshot];
        vc.colorHex = self.coverView.color.jk_HEXString;
        vc.coverType = self.coverView.coverType;
        
        CGFloat left = (self.view.jk_width - 144) * 0.5;
        CGFloat top = self.view.safeAreaInsets.top + 20;
        vc.imageView.frame = CGRectMake(left, top, 144, 176.84);
        
        @weakify(self)
        [self.navigationController wxs_pushViewController:vc makeTransition:^(WXSTransitionProperty *transition) {
            @strongify(self)
            transition.autoShowAndHideNavBar = NO;
            transition.animationType = WXSTransitionAnimationTypeViewMoveToNextVC;
            transition.animationTime = 0.5;
            transition.startView = self.coverView;
            transition.targetView = vc.imageView;
        }];
        
    });


}

@end
